package com.mpaster.meego.service;

import com.mpaster.meego.dao.UserRepository;
import com.mpaster.meego.entity.Role;
import com.mpaster.meego.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
@Transactional(rollbackOn = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public User save(User user) {
        return userRepository.save(user);
    }

    @Override
    public User findById(Long id) {
        return userRepository.findById(id).get();
    }

    @Override
    public List<User> findAll() {
        List<User> users = new ArrayList<>();
        userRepository.findAll().forEach(user -> users.add(user));
        return users;
    }

    @Override
    public List<User> findByLastName(String lastName) {
        List<User> users = new ArrayList<>();
        userRepository.findByLastName(lastName).forEach(user -> {
            users.add(user);
        });
        return users;
    }

    @Override
    public void assignRoles(User user, Set<Role> roles) {
        User persistUser = findById(user.getId());
        persistUser.getRoles().addAll(roles);
        userRepository.save(persistUser);
    }

    @Override
    public void deleteUser(String id) {
        userRepository.deleteById(Long.valueOf(id));
    }
}
